package ThreadDemo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-09
 * Time: 21:04
 */
public class ThreadDemo13 {
    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        //互相获取对方的锁，会造成死锁  约定同时获取同一个锁，解除死锁问题
        Thread t1 = new Thread(() -> {
            synchronized (lock1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lock2) {
                    System.out.println("t1 lock1 和 lock2 都获得了!");
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (lock1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lock2) {
                    System.out.println("t2 lock1 和 lock2 都获得了!");
                }
            }
        });

        t1.start();
        t2.start();
    }
}
